//
//  VerifyNumberVC.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/19/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.


import UIKit
import SnapKit


final class VerifyNumberVC: UIViewController, Alertable {

    // MARK: - Outlets

    private lazy var numberField: PaddingTextField = {
        let field = PaddingTextField()
        field.leftViewMode = .always
        field.leftView = self.createIconField(iconName: "call")
        field.delegate = self
        field.backgroundColor = .whiteBlueColor
        field.placeholder = "+7 (___) ___ __ __"
        field.keyboardType = .numberPad
        field.padding.left = 32
        field.tag = 1
        field.snp.makeConstraints { (make) in
            make.height.equalTo(48)
        }
        return field
    }()

    private lazy var submitBtn: LoadingButton = {
        let btn = LoadingButton()
        btn.clipsToBounds = true
        btn.layer.cornerRadius = 15
        btn.setTitle("Подтвердить", for: .normal)
        btn.snp.makeConstraints { (make) in
            make.height.equalTo(48)
        }
        return btn
    }()

    // MARK: - Props
   
    private let fullNumber = "+# (###) ### ## ##"
    private var isReady: Bool = false {
        didSet {
            if isReady {
                self.makeSubmitButtonBlue()
            } else {
                self.submitBtn.backgroundColor = .lightBlueColor
                self.submitBtn.setTitleColor(.greyColor, for: .normal)
            }
        }
    }
    
    // MARK: - UI Actions
    
    @objc private func goBack (sender: UIBarButtonItem) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func closeVC (sender: UIBarButtonItem) {
        self.navigationController?.dismiss(animated: true, completion: nil)
    }
    
    @objc private func screenTap (sender: UITapGestureRecognizer) {
        self.numberField.resignFirstResponder()
    }

    @objc private func onSubmit (sender: UIButton) {
        self.verifyNumber()
    }

    
    // MARK: - Life-Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.isReady = false
        self.setUpUI()
        self.setUpNavBar()
    }

}

// MARK: - Methods


extension VerifyNumberVC {
   
    private func addNumber (number: String) {
        var request = URLRequest(url: Request(base: .advert, addOffset: false).getUrl(path: "users/phones/"))
        request.httpMethod = "POST"
        let body = ["phone": number] as [String : Any]
        
        submitBtn.showLoading()
        
        Backend().fetchFromBackend(for: NumberViewModel.Number.self, request: request, statusCode: 201, sendBody: true, body: body) { (result) in
            self.submitBtn.hideLoading()
            self.submitBtn.setTitle("Готово", for: .normal)
            switch result {
            case .failure(let err):
                switch err {
                case .general:
                    self.showAlert("Упс...", "Неизвестная ошибка")
                case .parameter(let msg):
                    self.showAlert("Упс...", msg)
                }
            case .success(let number):
                NotificationCenter.default.post(name: NSNotification.Name("sendNumber"), object: nil, userInfo: ["data": number])
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    private func verifyNumber () {
        let pureNumber = (self.numberField.text ?? "").replacingOccurrences( of: "[^0-9]", with: "", options: .regularExpression)
        if pureNumber.count == 11 && pureNumber[...pureNumber.index(pureNumber.startIndex, offsetBy: 1)] == "77" {
            self.addNumber(number: pureNumber)
        } else {
            self.showAlert("Упс...", "Неверный формат номера")
        }
    }
}


// MARK: - UI

extension VerifyNumberVC {
    
    private func setUpUI () {
        view.backgroundColor = .white
        view.addSubview(numberField)
        view.addSubview(submitBtn)
        
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(screenTap(sender:)))
        view.addGestureRecognizer(tapGesture)
        
        numberField.addTarget(self, action: #selector(textDidChange(sender:)), for: .editingChanged)
        
        submitBtn.addTarget(self, action: #selector(onSubmit(sender:)), for: .touchUpInside)
        
        self.addConstraints()
        self.addCloseIcon()
    }
    
    private func addConstraints () {
        numberField.snp.makeConstraints { (make) in
            make.top.equalTo(view.safeAreaLayoutGuide).offset(30)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(48)
        }
        submitBtn.snp.makeConstraints { (make) in
            make.top.equalTo(numberField.snp.bottom).offset(24)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(44)
        }
    }
    
    private func setUpNavBar () {
        let backIcon = UIImage(named: "cancel")
        let backButton = UIBarButtonItem(image: backIcon, landscapeImagePhone: backIcon, style: .plain, target: self, action: #selector(goBack(sender:)))
        backButton.tintColor = .greyColor
        
        self.navigationItem.simpleNavBar(title: "Добавить номер", backButton: backButton)
        navigationItem.largeTitleDisplayMode = .always
        navigationController?.navigationBar.largeTitleTextAttributes = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 24, weight: .bold)
        ]
        navigationItem.hidesSearchBarWhenScrolling = false
        self.navigationController?.navigationItem.largeTitleDisplayMode = .always
    }

    private func createIconField (iconName: String) -> UIView {
        let view = UIView()
        let img = UIImageView()
        
        let image = UIImage(named: iconName)?.withRenderingMode(.alwaysTemplate)
        image?.sd_tintedImage(with: .darkBlueColor)
        
        img.image = image
        img.contentMode = .scaleAspectFit
        view.addSubview(img)
        img.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.width.height.equalTo(16)
            make.leading.equalToSuperview().offset(8)
        }
        view.snp.makeConstraints { (make) in
            make.width.equalTo(32)
            make.height.equalTo(16)
        }
        return view
    }
    
    
    private func makeSubmitButtonBlue () {
        UIView.animate(withDuration: 0.3, animations: {
            self.submitBtn.backgroundColor = .blueColor
            self.submitBtn.setTitleColor(.white, for: .normal)
        })
    }
    
    
    
    private func addCloseIcon () {
        let closeBarBnt = UIBarButtonItem(image: UIImage(named: "dismiss"), style: .plain, target: self, action: #selector(closeVC))
        closeBarBnt.tintColor = .greyColor
        self.navigationItem.rightBarButtonItem = closeBarBnt
    }
    
}


// MARK: - Text Field

extension VerifyNumberVC: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if numberField.tag == textField.tag {
            guard let text = textField.text else { return false }
            textField.text = text.applyPatternOnNumbers(pattern: "+# (###) ### ## ##", replacmentCharacter: "#")
            return true
        } else {
            return true
        }
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField.text!.isEmpty && numberField.tag == textField.tag {
            textField.text = "+7 (7"
        }
        return true
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    @objc private func textDidChange (sender: UITextField) {
        self.isReady = sender.text!.count == fullNumber.count
    }
}



